#include<bits/stdc++.h>
using namespace std;

struct Node{
    string s;
    int cnt;
    Node(){}
    Node(string s,int cnt){
        this->s=s;
        this->cnt=cnt;
    }
    bool operator<(const Node& node) const
    {
        return cnt>node.cnt;
    }
};

unordered_map<string,int> mp;
const string fin="123804765";
const vector<int> arr[9]={
    {1,3},{0,2,4},{1,5},
    {0,4,6},{1,3,5,7},{2,4,8},
    {3,7},{4,6,8},{5,7}
};
int main()
{
    string s;
    cin>>s;
    priority_queue<Node> que;
    mp[s]=0;
    que.push(Node(s,0));
    while (!que.empty()){
        Node node = que.top();
        que.pop();
        s = node.s;
        int cnt=node.cnt;
        if(cnt>mp[s]) continue;
        if(s==fin){
            cout<<cnt;
            return 0;
        }
        for(int c=0;s[c]!='\0';c++){
            if(s[c]=='0'){
                for(auto c1:arr[c]){
                    string ss=s;
                    ss[c]=s[c1];
                    ss[c1]=s[c];
                    if(!mp.count(ss)||(mp[ss]>cnt+1)){
                        mp[ss] = cnt+1;
                        que.push(Node(ss,cnt+1));
                    }
                }
            }
        }
    }
    cout<<mp[fin];
    return 0;
}